import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Spin, Form } from 'antd';
import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaSearchGroup,
  WeaDialog,
  WeaNewScroll,
  WeaFormItem,
  WeaLocaleProvider,
} from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import DocOfShare from './Tables/DocOfShare';
import TabPath from './Public/TabPath';
import { getPathOfTree } from '../util';

const { WeaTable } = WeaTableNew;
const { tryCatch } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
@tryCatch(
  React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@u5bh45`} msg={props.error || getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)
@inject('docShareStore', 'docDocShareStore')
@observer
class Share extends React.Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'wea-doc-share';
    this.isMouted = false;
    this.state={
      searchType:['base', 'advanced']
    }
  }
  componentDidMount() {
    this.isMouted = true;
    const { docShareStore } = this.props;
    docShareStore.getTreeDatas('Share')
      .getRightMenu('Share')
      .getConditionInfo('Share');
  }
  componentWillUnmount() {
    const { docShareStore } = this.props;
    docShareStore.setState({
      showSearchAd: false,
      showResult: false,
      selectedTreeKeys: [],
      tabPath: [],
    }).form.reset();
    this.isMouted = false;
  }
  onTabPathClick = (data = {}) => {
    const { docShareStore } = this.props;
    const { treeDatas, form } = docShareStore;
    const value = data.key || '';
    const valueSpan = data.name || '';
    form.updateFields({
      seccategory: {
        value,
        valueSpan,
        valueObj: [
          {
            id: value,
            name: valueSpan,
          },
        ],
      },
    });
    docShareStore.setState({
      selectedTreeKeys: data.domid ? [data.domid] : [],
      tabPath: getPathOfTree(toJS(treeDatas), data.domid),
    }).doSearch('Share', form.getFormParams());
  }
  onSearch=() => {
    const { docShareStore } = this.props;
    const { form, showResult, comsWeaTableStore } = docShareStore;
    docShareStore.doSearch('Share', form.getFormParams())
    .setState({ showSearchAd: false, showResult: true });
    comsWeaTableStore.setSelectedRowKeys([]);
  }
  getSearchs() {
    const { docShareStore } = this.props;
    const { conditioninfo, form } = docShareStore;
    const { isFormInit } = form;
    const group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(conditioninfo).forEach((c) => {
      let items = [];
      c.items.forEach((field) => {
        if (field.isQuickSearch) {
          this.quickSearchPara = field.domkey[0];
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jxvzt2@${field.domkey[0]}`}
              label={`${field.label}`}
              labelCol={{ span: field.labelcol }}
              wrapperCol={{ span: field.fieldcol }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5wde7f@${field.domkey[0]}`} fieldConfig={field} form={form} formParams={formParams} onEnterSearch={this.onSearch} />
            </WeaFormItem>
          ),
          colSpan: 1,
        });
      });
      group.push(
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@kpiei4@${c.title}`} needTigger={true} title={c.title} showGroup={true} items={items} />,
      );
    });
    return group;
  }
  getTabButtonsAd() {
    const { docShareStore } = this.props;
    const { form, showResult } = docShareStore;
    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ifniuo@search`} type="primary"
      onClick={this.onTabSearchClick}
    >{getLabel(197, '搜索')}</Button>];
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ggxqmb@reset`} type="ghost" onClick={this.onReset}>{getLabel(2022, '重置')}</Button>);
    showResult && btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yuh3wo@cancel`} type="ghost"
      onClick={this.onTabCancelCoick}
    >{getLabel(31129, '取消')}</Button>);
    return btns;
  }
  onReset=()=>{
    const { docShareStore } = this.props;
    const { form } = docShareStore;
    form.reset();
  }
  onTabSearchClick=() => {
    const { docShareStore } = this.props;
    const { form, comsWeaTableStore } = docShareStore;
    docShareStore.doSearch('Share', form.getFormParams())
      .setState({ showSearchAd: false, showResult: true });
    comsWeaTableStore.setSelectedRowKeys([]);
  }
  onTabCancelCoick=() => {
    const { docShareStore } = this.props;
    docShareStore.setState({ showSearchAd: false })
  }
  getRightMenu(isTop = false) {
    const { docShareStore, docDocShareStore } = this.props;
    const { rightMenu, comsWeaTableStore, form, loading, showResult } = docShareStore;
    const { selectedRowKeys } = comsWeaTableStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    const btnArr = [];
    rightMenu.forEach((m) => {
      let disabled = selectedRowKeys.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      if (m.type === 'BTN_SEARCH') { // 搜索
        disabled = false;
        onClick = () => {
          docShareStore.doSearch('Share', form.getFormParams())
            .setState({ showSearchAd: false, showResult: true });
        };
      } else if (m.type === 'BTN_NEXT') { // 下一步
        onClick = () => {
          docShareStore.setState({ showShareModal: true });
          docDocShareStore.getShareBatchChecks();
        };
      } else {
        disabled = false;
      }
      disabled = loadingNow || disabled;
      if (isTop) {
        m.isTop === '1' && showResult && btnArr.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mev9eg@${m.type}`} type="primary"
            disabled={disabled}
            onClick={onClick}
          >
            {content}
          </Button>,
        );
      } else if (!showResult) {
          m.type === 'BTN_SEARCH' && btnArr.push({
            key: m.type,
            icon: <i className={m.menuIcon} />,
            content,
            disabled,
            onClick,
          });
        } else {
          m.type !== 'BTN_STORE' && m.type !== 'BTN_HELP' && btnArr.push({
            key: m.type,
            icon: <i className={m.menuIcon} />,
            content,
            disabled,
            onClick,
          });
        }
    });
    return btnArr;
  }

  onFliterAll=() => {
    const { docShareStore } = this.props;
    const { treeDatas, form } = docShareStore;
    docShareStore.doSearch('Share')
      .setState({
        selectedTreeKeys: [],
        tabPath: getPathOfTree(toJS(treeDatas), ''),
      });
    form.reset();
  }
  onTreeSelect=(key, topTabCount, treeNode) => {
    const { docShareStore } = this.props;
    const { treeDatas, form } = docShareStore;
    let value = topTabCount.keyid;
    let valueSpan = '';
    const otherParams = {};
    if (treeNode.node) {
      value = treeNode.node.props.id;
      valueSpan = treeNode.node.props.name;
    } else {
      // 小数字 呵呵哒
      if (treeNode.name === 'newNum') {
        otherParams.isNew = 'yes';
      }
      treeDatas.forEach((d) => {
        if (d.domid === key) valueSpan = d.name;
      });
    }

    value = value || treeNode.node.props.data.key;

    form.updateFields({
      seccategory: {
        value,
        valueSpan,
        valueObj: [
          {
            id: value,
            name: valueSpan,
          },
        ],
      },
    });
    docShareStore.doSearch('Share', { ...otherParams, ...form.getFormParams(), seccategory: treeNode.node.props.data.key })
      .setState({
        selectedTreeKeys: [key],
        tabPath: getPathOfTree(toJS(treeDatas), key),
      });
  }
  getTree() {
    const { docShareStore } = this.props;
    const { treeDatas, treeTypes, treeCounts, form, treeLoading,
      selectedTreeKeys } = docShareStore;
    return (
      <div className="wea-doc-share-left-tree" style={{ height: '100%' }}>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@nt60qz`} spinning={treeLoading}>
          <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@1nyugk`}
            selectedKeys={toJS(selectedTreeKeys)}
            datas={toJS(treeDatas)}
            counts={treeCounts}
            countsType={toJS(treeTypes)}
            onFliterAll={this.onFliterAll}
            onSelect={this.onTreeSelect}
          />
        </Spin>
      </div>
    );
  }

  getDialogBtns=()=>{
   return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vufklb@saveShareBatch`} type="primary"
        onClick={this.saveShareBatch}
      >{getLabel(2191, '调整')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s8oyqo@cancel`} type="ghost"
        onClick={this.clear}
      >{getLabel(31129, '取消')}</Button>),
    ]
  }
  saveShareBatch=() => {
    const { docShareStore, docDocShareStore } = this.props;
    const {  form, comsWeaTableStore } = docShareStore;
    const { shareBatchDatas, shareBatchOpParams } = docDocShareStore;
    const { selectedRowKeys } = comsWeaTableStore;
    docDocShareStore.saveShareBatch({
      shareDatas: JSON.stringify(toJS(shareBatchDatas)),
      ...toJS(shareBatchOpParams),
      docid: `${selectedRowKeys}`,
    }, this.clear);
    docShareStore.doSearch('Share', form.getFormParams());
  }
  clear = () => {
    const { docShareStore, docDocShareStore } = this.props;
    docShareStore.setState({ showShareModal: false });
    docDocShareStore.setState({
      selectedKeys: [],
      shareBatchDatas: [],
      shareBatchOpParams: {},
    });
  };
  getShareModal() {
    const { docShareStore,  } = this.props;
    const { showShareModal, comsWeaTableStore } = docShareStore;
    const { selectedRowKeys } = comsWeaTableStore;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@z696e1`}
        className={`${this.prefixCls}-batch-modal`}
        title={getLabel(18037, '批量共享')}
        style={{ width: 800, height: 'auto' }}
        maskClosable={false}
        visible={showShareModal}
        onCancel={this.clear}
        icon={'icon-coms-doc'}
        iconBgcolor={'#f14a2d'}
        buttons={this.getDialogBtns()}
      >
        <DocOfShare ecId={`${this && this.props && this.props.ecId || ''}_DocOfShare@5f5spw`} type="batch" docid={`${selectedRowKeys}`} />
      </WeaDialog>
    );
  }
  getCollectParams=()=>{
    const { docShareStore } = this.props;
    const {title}=docShareStore;
    return {
      favname: title,
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/index.html#/main/document/share',
    }
  }
   getDropMenuProps=()=>{
    const { docShareStore } = this.props;
    const {title}=docShareStore;
    return {
      collectParams: {
        favname: title,
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/share',
      },
    }
   }
   getSearchBaseValue=()=>{
    const { docShareStore } = this.props;
     const {form}=docShareStore;
    return form.getFormParams()[this.quickSearchPara] || ''
   }
   setShowSearchAd=bool => {
    const { docShareStore } = this.props;
    docShareStore.setState({ showSearchAd: bool })
    }
    hideSearchAd=() =>{
      const { docShareStore } = this.props;
      docShareStore.setState({ showSearchAd: false })
      }
    onTabSearch=() => {
      const { docShareStore } = this.props;
     const {form}=docShareStore;
      docShareStore.doSearch('Share', form.getFormParams());
    }
    onSearchChange=value =>{
      const { docShareStore } = this.props;
      const {form}=docShareStore;
      form.updateFields({ [this.quickSearchPara]: { value } })
    }
    onCollapse=() => {
    const { docShareStore } = this.props;
    const {setState,collapse}=docShareStore;
    setState({ collapse: !collapse })
  }
  render() {
    const { docShareStore } = this.props;
    const { showSearchAd, loading, comsWeaTableStore, title, showResult,
      conditionLoading, tabPath, collapse } = docShareStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    return (
      <div className={this.prefixCls} >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@1035vp`}
          datas={this.getRightMenu()}
          collectParams={this.getCollectParams()}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@uxj1w5`}
            title={title}
            loading={showResult ? loadingNow : conditionLoading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={this.getRightMenu(true)}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={this.getDropMenuProps}
          >
            {showResult ?
              <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@fm21jp`}
                isNew={true}
                showLeft={collapse}
                onCollapse={this.onCollapse}
                leftCom={this.getTree()}
              >
                <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@scwtxc`}
                  buttonsAd={this.getTabButtonsAd()}
                  searchType={this.state.searchType}
                  searchsBaseValue={this.getSearchBaseValue()}
                  searchsAd={this.getSearchs()}
                  showSearchAd={showSearchAd}
                  setShowSearchAd={this.setShowSearchAd}
                  hideSearchAd={this.hideSearchAd}
                  onSearch={this.onTabSearch}
                  onSearchChange={this.onSearchChange}
                />
                <TabPath ecId={`${this && this.props && this.props.ecId || ''}_TabPath@1144f1`} paths={toJS(tabPath)} onClick={this.onTabPathClick} />
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@hwacay`}
                  comsWeaTableStore={comsWeaTableStore}
                  hasOrder={true}
                  needScroll={true}
                />
              </WeaLeftRightLayout>
              :
              <div className={`${this.prefixCls}-search`} >
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@82278j`} height="100%" >
                  {this.getSearchs()}
                </WeaNewScroll>
                <div className={`${this.prefixCls}-search-btns`}>
                  {this.getTabButtonsAd()}
                </div>
              </div>
            }
          </WeaTop>
        </WeaRightMenu>
        {this.getShareModal()}
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@g7izwy`} pathname="/document/share" secid="-1" docid="-1" />
      </div>
    );
  }
}

export default Share;
